const express = require('express')
const { createProxyMiddleware } = require('http-proxy-middleware')
const cors = require('cors')

const app = express()
const PORT = 3001

// 启用CORS
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['*']
}))

// 解析请求体
app.use(express.json({ limit: '50mb' }))
app.use(express.urlencoded({ extended: true, limit: '50mb' }))
app.use(express.raw({ limit: '50mb' }))
app.use(express.text({ limit: '50mb' }))

// 通用代理路由
app.use('/proxy', (req, res, next) => {
  const targetUrl = req.query.url || req.headers['x-target-url']
  
  if (!targetUrl) {
    return res.status(400).json({ error: 'Missing target URL' })
  }

  try {
    const url = new URL(targetUrl)
    const proxy = createProxyMiddleware({
      target: `${url.protocol}//${url.host}`,
      changeOrigin: true,
      pathRewrite: {
        '^/proxy': url.pathname + (url.search || '')
      },
      onProxyReq: (proxyReq, req, res) => {
        // 移除代理相关的头部
        proxyReq.removeHeader('x-target-url')
        
        // 处理请求体
        if (req.body && (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH')) {
          const bodyData = typeof req.body === 'string' ? req.body : JSON.stringify(req.body)
          proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
          proxyReq.write(bodyData)
        }
        
        console.log(`Proxying ${req.method} ${targetUrl}`)
      },
      onError: (err, req, res) => {
        console.error('Proxy error:', err.message)
        res.status(500).json({ error: 'Proxy error: ' + err.message })
      }
    })
    
    proxy(req, res, next)
  } catch (error) {
    res.status(400).json({ error: 'Invalid URL: ' + error.message })
  }
})

app.listen(PORT, () => {
  console.log(`Proxy server running on http://localhost:${PORT}`)
})